using System.Collections.Generic;
using System.Linq;
using Core;
using IglooCoder.Commons.WcfNhibernate;
using NHibernate;
using NHibernate.Linq;

namespace Infrastucture
{
    public class MutasiWarehouseRepository : BaseNHibernateRepository<MutasiWarehouse>
    {
        public MutasiWarehouseRepository(ISessionStorage sessionStorage)
            : base(sessionStorage)
        {
        }


        public string GetMaxNumber(string kodeAwal)
        {
            string res = string.Empty;
            var lenKode = kodeAwal.Length + 10;
            var query = Session.CreateSQLQuery("Select Max(NoMutasi) as Number from MutasiWarehouse  where NoMutasi like'" + kodeAwal + "%' AND  Len(NoMutasi)=" + lenKode).AddScalar("Number", NHibernateUtil.String);
            var objRes = query.List()[0];
            if (objRes != null) res = objRes.ToString();
            return res;
        }

        public void UpdateStatus(string NoMutasi, int Status)
        {
            ISQLQuery command =
            Session.CreateSQLQuery("Update MutasiWarehouse set Status=" + Status + " Where NoMutasi='" + NoMutasi + "'");
            int res = command.ExecuteUpdate();
        }

        public void UpdateEmailStatus(string NoMutasi)
        {
            ISQLQuery command =
            Session.CreateSQLQuery("Update MutasiWarehouse set HasSent=1 Where NoMutasi='" + NoMutasi + "'");
            int res = command.ExecuteUpdate();
        }

        public virtual IList<MutasiWarehouse> GetDataPaged(int page, int pageSize, string sortProperty, string sortType)
        {

            PagedList<MutasiWarehouse> Results;
            using (var tx = Session.BeginTransaction())
            {
                if (sortType.ToUpper() == "ASC")
                {
                    Results = Session.Linq<MutasiWarehouse>().ApplyOrder(sortProperty, "OrderBy").ToPagedList(page, pageSize);
                }
                else
                {
                    Results = Session.Linq<MutasiWarehouse>().ApplyOrder(sortProperty, "OrderByDescending").ToPagedList(page, pageSize);
                }

                tx.Commit();
            }

            RecordCount = Results.TotalCount;
            return Results;
        }
    }
}